package com.example.demo.domain.platform;

import com.example.demo.domain.application.Application;
import com.example.demo.domain.platform.repository.PlatformReleaseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 平台服务
 * @author yingjianhua
 */
@Service
public class PlatformService {

    @Autowired
    private PlatformReleaseRepository platformReleaseRepository;

    /**
     * 发布
     *
     * @param application 应用
     * @param platform    平台
     * @param releaseType 发布方式
     * @param releaseCode 发布code
     * @return 发布信息
     */
    public PlatformRelease release(Application application, Platform platform, PlatformRelease.ReleaseType releaseType, String releaseCode) {
        PlatformRelease platformRelease;
        Optional<PlatformRelease> releaseOptional = platformReleaseRepository.findByApplicationAndPlatform(application, platform);
        if (releaseOptional.isPresent() && !(platformRelease = releaseOptional.get()).getReleased()) {
            // 假如应用是已经发布过，后来下架了，只需要修改发布信息为已发布就好了
            platformRelease.release();
        } else {
            // 如果应用是第一次发布， 需要新增一条发布信息
            platformRelease = new PlatformRelease(application, platform, releaseType, releaseCode, true);
            platformReleaseRepository.save(platformRelease);
        }
        return platformRelease;
    }

    /**
     * 下架
     *
     * @param application 应用
     * @param platform    平台
     * @return 发布信息
     */
    public PlatformRelease remove(Application application, Platform platform) {
        PlatformRelease platformRelease = platformReleaseRepository.findByApplicationAndPlatform(application, platform).orElseThrow(() -> new RuntimeException("应用还没有发布过，不能下架"));
        if (platformRelease.getReleased()) {
            platformRelease.remove();
            return platformRelease;
        } else {
            throw new RuntimeException("该应用已经下架了");
        }
    }

    /**
     * 获取应用的发布信息
     *
     * @param application 应用
     * @return 发布信息
     */
    public List<PlatformRelease> getReleaseInfo(Application application) {
        List<PlatformRelease> platformReleases = new ArrayList<>();
        for (Platform platform : Platform.values()) {
            Optional<PlatformRelease> releaseOptional = platformReleaseRepository.findByApplicationAndPlatform(application, platform);
            releaseOptional.ifPresent(platformReleases::add);
        }
        return platformReleases;
    }

    /**
     * 获取应用在指定平台的发布信息
     *
     * @param application 应用
     * @param platform    平台
     * @return 发布信息
     */
    public Optional<PlatformRelease> getReleaseInfo(Application application, Platform platform) {
        return platformReleaseRepository.findByApplicationAndPlatform(application, platform);
    }
}
